﻿using StudentControlSystem.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SQLite;

namespace StudentControlSystem.Controller
{
    internal class SchoolController
    {
        string connectionString = DBHelper.ConnStrings;
        //新增学校
        public void AddSchool(School school)
        {
            
            using (var connection = new SQLiteConnection(connectionString))
            {
                connection.Open();
                var command = new SQLiteCommand("INSERT INTO Schools (Name) VALUES (@name)", connection);
                command.Parameters.AddWithValue("@name", school.Name);
                command.ExecuteNonQuery();
                Log.LogAction("Added school: " + school.Name);
            }
        }

        //更新
        public void UpdateSchool(School school)
        {
            using (var connection = new SQLiteConnection(connectionString))
            {
                connection.Open();
                var command = new SQLiteCommand("UPDATE Schools SET Name = @name WHERE SchoolId = @id", connection);
                command.Parameters.AddWithValue("@name", school.Name);
                command.Parameters.AddWithValue("@id", school.SchoolId);
                command.ExecuteNonQuery();
                Log.LogAction("Updated school: " + school.Name);
            }
        }

        //删除
        public void DeleteSchool(int schoolId)
        {
            using (var connection = new SQLiteConnection(connectionString))
            {
                connection.Open();
                var command = new SQLiteCommand("DELETE FROM Schools WHERE SchoolId = @id", connection);
                command.Parameters.AddWithValue("@id", schoolId);
                command.ExecuteNonQuery();
                Log.LogAction("Deleted school with ID: " + schoolId);
            }
        }

        public School GetById(int schoolId)
        {
            School school = null;
            using (var connection = new SQLiteConnection(connectionString))
            {
                connection.Open();
                var command = new SQLiteCommand("SELECT * FROM Schools WHERE SchoolId = @id", connection);
                command.Parameters.AddWithValue("@id", schoolId);
                using (var reader = command.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        school = new School
                        {
                            SchoolId = reader.GetInt32(0),
                            Name = reader.GetString(1)
                        };
                    }
                }
            }
            return school;
        }

        
    }


}
